package org.groupg.practice.configuration;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class ConfigLoader {
    public static PropertiesConfiguration loadConfig() throws ConfigurationException {
        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                        .configure(params.properties()
                                .setURL(ConfigLoader.class.getResource("/config.properties")));
        return builder.getConfiguration();
    }

    public static void main(String[] args) {
        PropertiesConfiguration config = null;
        try {
            config = ConfigLoader.loadConfig();
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }

// 方式1：读取逗号分隔的数组
        String[] modules = config.getStringArray("app.modules");

// 方式2：读取带索引的数组
        List<Object> hosts = config.getList("app.hosts");

// 打印结果
        System.out.println(Arrays.toString(modules)); // [core, web, db]
        System.out.println(hosts); // [192.168.1.1, 192.168.1.2]

        String filePath = config.getString("data.file");

        if (filePath != null && filePath.startsWith("classpath:")) {
            String resourcePath = filePath.substring("classpath:".length());
            try (InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream(resourcePath)) {
                if (input != null) {
                    String content = IOUtils.toString(input, StandardCharsets.UTF_8);
                    System.out.println("File content:\n" + content);
                } else {
                    System.out.println("Resource not found: " + resourcePath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}